/**
 * 计划书分享界面主操作
 */
var $Document, _pro_id = '2',
	_sch = document.body.scrollHeight,
	_vh = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
	_vw = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var $ddContent;
$(function() {
	$Document = $(document);
	//将界面中所有a 页签的 href为空的修改成javascript:void(0);
	$('a[href=""]').attr({href:"javascript:void(0);"});
	$('.detailed-description,.input-containt').css({
		'height': _sch
	});
	$ddContent = $('.detailed-description .content-text').css({
		'height': _vh * 0.65
	});
	$('.nav-insurance-info >img').css({
		'width': _vw
	});
	//计算滚动高度，修改侧边按钮的透明度
	window.onscroll = winScroll;
	//顶部计划书与专业顾问导航切换
	bindingEvent('nav li', function(e) {
		changeNavLiActive($(e.target));
		return _stopDefaultEvent(e);
	});
	//侧边框/底部经理人信息切换
	bindingEvent('.side-position,.cnt-prospectus .manager-info .img-poto', function(e) {
		//$('.nav-li-professionalcon')[0].tap();
		changeNavLiActive($('.nav-li-professionalcon'));
		$('.side-position').hide();
		return _stopDefaultEvent(e);
	});
	//点击弹出详细信息后，按钮关闭装口
	bindingEvent('.detailed-description .btn', function(e) {
		$('.detailed-description').hide();
		window.onscroll = winScroll;
		return _stopDefaultEvent(e);
	});
	//点击条款说明弹出信息
	bindingEvent('.side-btn', function(e) {
		var pu = $('.detailed-description .content-text').attr('data-pdf-url');
		if (pu) {
			//window.open('pdf.html?pdf=' + pu);
			window.open(pu);
		} else {
			$('.detailed-description').show();
			window.onscroll = null;
		}
		return _stopDefaultEvent(e);
	});
	/*//电话点击，弹出拨号信息
	bindingEvent('.phone a', function(e) {
		return _stopDefaultEvent(e);
	});*/
	//点击界面上需要修改值的地方
	/*bindingEvent('.btn-input', function(e) {
		var tar = $(e.target),
			_ip = tar.attr('data-input-placeholder'),
			_it = tar.attr('data-input-title'),
			_ig = tar.attr('data-input-target') || tar.attr('data-url-param');
		var $ic = $('.input-containt'),
			$icItem = $ic.find('.input-containt-item'),
			$icContext = $ic.find('.input-containt-context'),
			$icInput = $ic.find('.input-containt-item input'),
			$ok = $ic.find('.btn-ok');
		//调整数字选择框
		if (_ig == 'total_year') {
			$icItem.empty();
			var strHTML = ['<li>选择缴费年限</li>'];
			for (var k in _period_payment) {
				strHTML.push('<li data-value="' + k + '">' + _period_payment[k] + '</li>');
			}
			$icItem.html(strHTML.join(''));
			$icContext.css({
				'height': '340px',
				'margin-top': '72px'
			});
		} else {
			if ($icInput.length == 0) {
				$icItem.empty();
				$icItem.append('<input type="text" placeholder="" />');
			}
			$icContext.css({
				'height': '150px',
				'margin-top': '120px'
			});
		}

		_it ? $ic.find('label.title').html(_it).show() : $ic.find('label.title').hide();
		_ip ? $icInput.attr({
			'placeholder': _ip
		}).val('') : '';
		_ig ? $ok.data('data-target', _ig) : $ok.removeAttr('data-target');
		$ic.find('input').focus();
		$ic.show();
		return _stopDefaultEvent(e);
	});
	//输入修改数据取消按钮事件
	bindingEvent('.input-containt .btn-cancel', function(e) {
		$('.input-containt').hide();
		console.log('隐藏');
		return _stopDefaultEvent(e);
	});
	//输入修改数据确定按钮事件
	bindingEvent('.input-containt .btn-ok', function(e) {
		var tar = $(e.target),
			_tg = tar.data('data-target');
		var $ic = $('.input-containt'),
			$iv = $ic.find('.input-containt-item input').val(),
			$sv = $ic.find('.input-containt-item li.active').attr('data-value'),
			$tgDom = _tg ? $('.btn-input.' + _tg) : '';

		if (_tg == 'total_year' && $sv) { //有值才填充
			$tgDom ? $tgDom.html($sv == '999' ? '趸缴' : $sv) : '';
		} else if (_tg != 'total_year' && $iv) { //有值才填充
			$tgDom ? $tgDom.html($iv) : '';
		}
		$ic.hide();
		if (_tg == 'guessage') {
			calculatePremium();
		} else {
			reCalculationRateToDom();
		}
		return _stopDefaultEvent(e);
	});*/
	//男女切换事件
	/*bindingEvent('.np-tab li', function(e) {
		var tar = $(e.target),
			ls = $('.np-tab li');
		ls.removeClass('active');
		tar.addClass('active');
		//reCalculationRateToDom();
		return _stopDefaultEvent(e);
	});*/
	//绑定缴费期限选择项选中事件
	/*bindingEvent('.input-containt-item li', function(e) {
		var tar = $(e.target),
			sv = tar.attr('data-value');
		if (!sv) {
			return _stopDefaultEvent(e);
		}
		$('.input-containt-item li').removeClass('active');
		tar.addClass('active');
		return _stopDefaultEvent(e);
	});*/
	//从地址参数中获取险种ID号
	_pro_id = getURLParam('pro_id') || _pro_id;
	/*//弹出窗口确定按钮事件
	bindingEvent('.k-layer .btn-ok',function(){
		var $ic=$('.k-layer').hide();
		$ic.find('.title').empty();
		$ic.find('.context').empty();
		return _stopDefaultEvent(e);
	});*/
	getUrlParamValueToInitDom();
	formatDomTextNumber();
	//如果当前浏览是使用微信，就调用更新回执
	setTimeout(function() {
		var _d = $.__detect;
		if (_d && _d.browser && _d.browser.weixin) {
			callInterfaceToUpdateReceipt(getURLParam('planId'));
		}
	}, 0);
	/*$.ajax({
		type: "get",
		url: _SERVER_IP,
		async: true,
		data: {
			pro_id: 8,
			sex: 1,
			age: 16,
			total_year: 3,
			total: 100000
		},
		dataType: 'jsonp',
		jsonp: 'callback', //服务器端获取回调函数名的key，对应后台有$_GET['callback']='getName';callback是默认值
		jsonpCallback: 'cb', //回调函数名
		success: function(result) { //成功执行处理，对应后台返回的getName(data)方法。
			console.log(result);
		},
		error: function(msg) {
			alert(msg.toSource()); //执行错误
		}
	});*/
});
/*
 * 调用接口更新回执信息,只是get请求对应的路径即可
 * @param rid 回执ID号
 */

function callInterfaceToUpdateReceipt(rid) {
	if (rid) {
		var iframe = document.createElement('iframe');
		iframe.style.display = "none";
		iframe.src = _SERVER_IP + '?planid=' + rid;
		document.body.appendChild(iframe);
	}
}
/**
 * 绑定事件
 * @param {Object} $selector 待绑定事件的选择器
 * @param {Object} callback 事件触发回调函数
 * @param {Object} type 事件类型，默认为tap touchend
 */

function bindingEvent($selector, callback, type) {
	//type = type || 'tap touchend';
	type = type || 'touchend'; //注意，触发事件tap后也会触发touchend事件，需要去掉一个
	$Document.off(type, $selector).on(type, $selector, callback || function(e) {});
}
/**
 * 重新计算费率
 */

function reCalculationRateToDom() {
	calculationRate($('.btn-input.age')[0].innerHTML,
		$('.btn-input.guessage')[0].innerHTML,
		$('.btn-input.total_year')[0].innerHTML,
		$('.btn-input.total')[0].innerHTML,
		$('.np-tab-sex.active').attr('data-url-value'),
		backfillRateToDom);
}
/**
 * 回填数据到界面Dom
 * @param {Object} rd 数据集
 */

function backfillRateToDom(rd) {
	var $c = $('.nav-plan-content');
	$c.find('.yearPayable').html(rd['yearPayable']);
	$c.find('.paySeriousillness').html(rd['paySeriousillness']);
	$c.find('.payMinorillness').html(rd['payMinorillness']);
	formatDomTextNumber();
}
/**
 * 文档的滚动事件
 */

function winScroll() {
	var cp = document.documentElement.scrollTop || document.body.scrollTop;
	$('.side-position').css({
		'opacity': (cp < 100 ? 0 : (cp / _sch + 0.4))
	});
	if ($ddContent.css('display') == 'block') { //显示的时候才实时滚动
		$ddContent.css({
			'margin-top': _vh * 0.1 + cp
		});
	}
}
/**
 * 切换顶部页签选项
 * @param {Object} $dom zepto对象DOM
 */

function changeNavLiActive($dom) {
	if ($dom) {
		var tgc = $dom.attr('target-code');
		$('nav li').removeClass('active');
		$dom.addClass('active');
		window.scrollTo(0, 0);
		if (tgc == '1') {
			$('.cnt-prospectus').addClass('active');
			$('.cnt-professionalcon').removeClass('active');
			$('.side-position').show();
		}
		if (tgc == '2') {
			$('.cnt-prospectus').removeClass('active');
			$('.cnt-professionalcon').addClass('active');
		}
	}
}
/**
 * 获取地址栏参数初始化界面DOM值
 */

function getUrlParamValueToInitDom() {
	$('.url-param').each(function(ind) {
		var tar = $(this),
			p = tar.attr('data-url-param'),
			v = getURLParam(p);
		v = v ? decodeURIComponent(v) : v; //对传递的参数中文进行解码
		if (p == 'sex') { //性别单独处理，用于切换界面上男女选项
			v = v || '1';
			tar.find('li').each(function(i) {
				var t = $(this),
					vd = t.attr('data-url-value');
				t.removeClass('active');
				if (vd == v) {
					t.addClass('active');
				}
			});
		} else if (p == 'userInfo' && v) { //经理人信息单独处理
			var b64 = new Base64(),
				user = b64.decode(v);
			if (user) {
				user = user.split(','); //值顺序为：headUrl(头像),realname(姓名),company(公司),phone(手机号),weichat(微信号)
				var $mi = $('.manager-info');
				$mi.find('.dup').each(function(idx) {
					var t = $(this),
						dp = t.attr('data-param'),
						ui = user[idx];
					/*dp == 'headUrl' ? t.attr({
						'src': ui
					}) : t.html(ui);*/
					dp == 'headUrl' ? loadHeadPoto(ui) : t.html('<em>'+(ui == '()' ? '未设置' : ui)+'</em>');
					if (dp == 'phone') {
						ui ? '' : $mi.find('.i-phone').hide();
						t.attr({
							'href': 'tel:' + ui
						}).html(formatPhone && ui.length == 11 ? formatPhone(ui, '###-####-####') : ui);
					}
					if (dp == 'weichat') {
						ui ? '' : $mi.find('.i-comments').hide();
						t.attr({
							'href': 'javascript:void(0);' //'weixin://addfriend/' + ui
						});
					}
				});
			}
		} else {
			v ? tar.html(v || '') : '';
		}
	});
	//填充完数据后将新的模板复制到专业顾问界面
	$('.cnt-professionalcon .manager-info').html($('.cnt-prospectus .manager-info').html());
}
/**
 * 格式化对应的数字成千分符
 */

function formatDomTextNumber() {
	$('.format-number').each(function(ind) {
		var tar = $(this),
			t = tar.html();
		tar.html(formatNumber(t));
	});
}
/**
 * 计算费率
 * @param {Integer} age 年龄
 * @param {Integer} guessage 测算年龄
 * @param {Integer} tyear 缴费期限
 * @param {Integer} total 保障金额
 * @param {Integer} sex 性别(1男0女)
 */

function calculationRate(age, guessage, tyear, total, sex, callback) {
	callback({
		yearPayable: getRandom(0, 3000),
		paySeriousillness: getRandom(0, 9999999),
		payMinorillness: getRandom(0, 999999)
	});
}
/**
 * 利益演示重新计算
 */

function calculatePremium() {
	var a = $Document.find('.btn-input.age').html(),
		b = $Document.find('.btn-input.guessage').html(),
		m = $Document.find('.btn-input.total').html(),
		k = $Document.find('.btn-input.total_year').html(),
		c = $Document.find('.format-number.yearPayable').html(),
		t = _pro_id;
	m = m.replace(',', '');
	c = c.replace(',', '');

	//alert(_profitFormula(a, b, m, k, c, t));
}
/**
 * 利益演示计算公式
 * @param {Integer} a 年龄
 * @param {Integer} b 利益演示年龄
 * @param {Integer} m 保障金额
 * @param {Integer} k 缴费期限
 * @param {Integer} c 保费
 * @param {Integer} t 险种类型
 */

function _profitFormula(a, b, m, k, c, t) {
	var sum = 0;
	k = k == '趸交' ? k : parseInt(k);
	a = parseInt(a);
	b = parseInt(b);
	m = parseInt(m);
	c = parseInt(c);
	t = parseInt(t);
	switch (t) {
		case 1: //中宏金裕年年A
			if (b <= 59) sum = (b - a - 4) * m * .05;
			else if (b <= 60) sum = (59 - a - 4) * m * 0.05 + m;
			else if (b > 60) sum = (59 - a - 4) * m * 0.05 + m + (b - 60) * m * .15;
			break;
		case 2: //中宏为爱启航利益一
			if (b < 18) sum = (b - a - 2) * m;
			else if (b < 22) sum = (17 - a - 2) * m + (b - 17) * m * 6;
			else if (b < 31) sum = (17 - a - 2) * m + 4 * m * 6 + (b - 21) * m;
			break;
		case 3: //中宏为爱启航利益二
			if (k == '趸交') sum = c - 24 * m;
			else if (k == 3 || k == 5 || k == 10) sum = k * c - 24 * m;
			else if (k == '至18') sum = (k - a - 2) * c - 24 * m;
			break;
		case 4: //中宏陪伴成长
			if (b < 18) sum = m * .2 + (b - a) * m;
			else if (b < 22) sum = m * .2 + (17 - a) * m + (b - 17) * m * 6;
			else if (b < 60) sum = m * .2 + (17 - a) * m + 4 * m * 6 + (b - 21) * m;
			else if (b < 61) sum = m * .2 + (17 - a) * m + 4 * m * 6 + (b - 21) * m + (c - 24 * m);
			else if (b < 101) sum = m * .2 + (17 - a) * m + 4 * m * 6 + (b - 21) * m + (c - 24 * m) + (b - 60) * m;
			break;
		case 5:
			break;
		case 6:
			break;
		default:
			break;
	}
	return sum;
}
/**
 * 加载头像图片
 * @param {Object} url 图片路径
 */

function loadHeadPoto(url) {
	var img = document.createElement('img');
	img.src = url;
	img.onload = function() {
		$('.img-poto img').attr({
			'src': url
		})
	}
}